﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.DataAccess;
using MShop.Core.Domain;
using MShop.Web.Components.Paging;
using MShop.Core;

namespace MShop.Web.Controllers
{
    public class ArticleController : ControllerBase
    { 
        private readonly IArticleDao _ArticleDao;
        private readonly ICommonDao<ArticleCategory> _CommonDao;
        private readonly IShopContext _IShopContext;        
        public ArticleController(IArticleDao articleDao, ICommonDao<ArticleCategory> commonDao,IShopContext shopContext) 
        {            
            _ArticleDao = articleDao;
            _CommonDao = commonDao;
            _IShopContext = shopContext;
        }

         [OutputCache(VaryByParam = "Id;page", Duration = 600)]
        public ActionResult Index(int? page,int? id)
        {
            
            AppendMeta("资讯中心","进口红酒信息,葡萄酒,红酒知识,红酒品牌,红酒的好处,葡萄酒的制作方法,葡萄酒价格","资讯中心主要展示红酒的相关信息,包括红酒文化,年鉴,收藏,庄园,历史,法规,生活等");
            ViewData["articlecatgories"] = _CommonDao.Find(x => x.Sort<100);

            var query = _ArticleDao.Find(x=>x.ArticleCategory.Sort<100);

            if (id.HasValue)
            {
                query = from item in query where item.CId == id.Value select item;
            }
            int pageindex = 0;
            if (page.HasValue)
            {
                pageindex = page.Value-1;
            }
            PagedList<Article> pagedlist = new PagedList<Article>(query.OrderByDescending(x => x.Created), pageindex, _IShopContext.Settings.WebSitePageSize);
            return View(pagedlist);
        }

        [OutputCache(VaryByParam="Id",Duration=600)]
        public ActionResult Item(int id)
        {
            Article article = _ArticleDao.GetById(id);
            ViewData["articlecatgories"] = _CommonDao.Find(x => x.Sort < 100);
            string description = string.IsNullOrEmpty(article.Summary) ? article.SlashEncodeContent(120) : article.Summary;
            AppendMeta(string.Concat(article.Title.Trim(), "-", article.ArticleCategory.Name, "-资讯中心"), article.Title.Trim(), description);
            article.Click++;
            _ArticleDao.SaveChanges();
            return View(article);
        }

        [OutputCache(VaryByParam = "cid", Duration = 600)]
        public ActionResult TopArticle(int cid)
        { 
            IQueryable<Article> articles = _ArticleDao.Find(x => x.CId == cid).OrderByDescending(x => x.Click).Take(10);
            return PartialView("article/toparticle",articles);
        }

        [OutputCache(VaryByParam = "cid", Duration = 600)]
        public ActionResult NewArticle(int cid)
        {
            IQueryable<Article> articles = _ArticleDao.Find(x => x.CId == cid).OrderByDescending(x => x.Created).Take(10);
            return PartialView("article/toparticle", articles);
        }
    }
}
